<template>
  <msg-captcha
    v-model="bindPhoneNumberShow"
    :captcha-type="isInWx() ? 'BIND_PHONE_NUMBER_MSG_CODE' : 'BIND_MSG_CODE'"
    @bind="onBind"
  />
</template>

<script lang="ts" setup>
import { isInWx } from '../../utils/wx'
import MsgCaptcha from '@/framework/components/MsgCaptcha/index.vue'
import { bindWxPhoneNumber } from '@/framework/apis/wx'
import { bindPhoneNumber, getUserInfo } from '@/framework/apis/login'
import { useUserStore } from '@/framework/store/user'

const props = withDefaults(
  defineProps<{
    modelValue: boolean
  }>(),
  {
    modelValue: false
  }
)
const emit = defineEmits<{
  (e: 'update:modelValue', value: any): void
  (e: 'finish'): void
}>()
const { modelValue } = toRefs(props)
const userStore = useUserStore()
const bindPhoneNumberShow = ref(modelValue.value)
watch(
  () => bindPhoneNumberShow.value,
  () => emit('update:modelValue', bindPhoneNumberShow.value)
)
watch(
  () => modelValue.value,
  () => (bindPhoneNumberShow.value = modelValue.value)
)
const onBind = (phoneNumber: any, smsCode: any) => {
  if (isInWx()) {
    bindWxPhoneNumber(phoneNumber, smsCode).then(() => {
      bindPhoneNumberShow.value = false
      getUserInfo().then((res) => userStore.setInfo(res.payload))
      emit('finish')
    })
  } else {
    bindPhoneNumber(phoneNumber, smsCode).then(() => {
      bindPhoneNumberShow.value = false
      getUserInfo().then((res) => userStore.setInfo(res.payload))
      emit('finish')
    })
  }
}
onMounted(() => {
})
</script>

<style lang="less" scoped>

</style>
